<?php
declare (strict_types=1);

namespace app\listener;

use app\common\job\LawyerResponseStatistics;
use app\common\model\Consulting;
use app\common\model\ConsultingQuestion;
use app\common\model\Member;
use app\common\service\DouyinMiniProgramMessageService;
use app\common\service\MiniProgramMessageService;
use app\common\service\SubscriptionMessageService;
use app\common\service\TemplateSmsService;
use app\index\service\QuestionService;
use app\index\traits\ChatFreelyTrait;
use ShidianUtil\Concurrent\Synchronizer;
use ShidianUtil\Utils\CheckUtil;
use think\facade\Queue;

class ConsultingMemberMessageCreated
{
    use ChatFreelyTrait;


    /**
     * 用户主动发送消息创建 事件监听处理
     *
     * @return mixed
     */
    public function handle($params)
    {
        $user = $params['user'] ?? null;
        $message = $params['message'] ?? null;
        $consultingId = $params['consultingId'] ?? null;

        $signature = __CLASS__ . $consultingId;
        $this->getSynchronizer()->synchronized($signature, function () use ($user, $message, $consultingId) {

            $messageType = $message->messageType;
            $contentStr = messageContentStr($messageType, $message->content);
            $now = time();

            $consulting = Consulting::where('id', $consultingId)->find();

            // 用户的消息
            if ($user->type == 0) {

                $isAsked = $consulting->isAsked;

                if ($isAsked == '0') {
                    // 首句提问

                    // 生成问题
                    $question = $this->getQuestionService()->saveQuestion($user->id, $contentStr, $consulting->categoryId, '', ConsultingQuestion::FROM_CONSULTING, true,
                        '', $consulting->pf, $consulting->chain, $consulting->promotionGroupId);

                    // 绑定问题
                    $consulting->isAsked = '1';
                    $consulting->ask = $question->ask;
                    $consulting->questionId = $question->id;
                    $consulting->save();

                    // 触发 问题绑定 事件
                    event('ConsultingQuestionBind', $consulting);

                    // 如果已指定律师，那么推送公众号模板消息
                    if (is_id($consulting->lawyerId)) {
                        $pagepath = 'pages/lawyer/lawyer?confirm_id=' . $consultingId;
                        $userName = $user->nickname;
                        $this->getSubscriptionMessageService()->messageFreeConsulting($consulting->lawyerId, $userName, $consulting->ask, $now, 120, $pagepath);
                    }

                } else {
                    // 追问

                    $isChatFreely = $this->isChatFreely($consulting);

                    // 扣减次数
                    if (!$isChatFreely && $consulting->questionsNum > 0) {

                        $consulting->questionsNum = $consulting->questionsNum - 1;
                        $consulting->save();

                    }

                    // 如果追问的时候存在律师，那么给律师发公众号模板消息
                    if (is_id($consulting->lawyerId) && $consulting->rushStatus == 2) {
                        $pagepath = 'pages/lawyer/lawyer?confirm_id=' . $consulting->id;
                        $this->getSubscriptionMessageService()->messageAsk($consulting->lawyerId, $user->nickname, $consulting->ask, $contentStr, $now, $pagepath);
                    }

                    // 判断次数
                    if (!$isChatFreely && $consulting->questionsNum <= 0) {
                        // 触发剩余次数不足
                        event('ConsultingQuestionNumNotEnough', $consulting);
                    }
                }

            }

            // 律师的消息
            if ($user->type == 1) {

                if ($consulting->isAnswered != 1) {
                    // 置为已回答
                    $consulting->isAnswered = 1;
                    $consulting->rushStatus = 2;
                    $consulting->responseTimeLength = time() - $consulting->rushTime;
                    $consulting->save();

                    // 律师首次回答，给用户发短信通知
                    $phone = Member::where('id', $consulting->memberId)->value('phone');
                    if (CheckUtil::isPhoneNumber($phone)) {
                        $this->getTemplateSmsService()->lawyerReply($phone);
                    }

                    // 律师数据统计
                    $job_data = ['id' => $user->id];
                    Queue::push(LawyerResponseStatistics::class, $job_data);
                }

                // 发小程序订阅消息
                $this->getMiniProgramMessageService()->messageLawyerFirstReplay($consulting->memberId, $contentStr, $user->realname, $now);

                // 抖音小程序订阅消息
                $this->getDouyinMiniProgramMessageService()->messageLawyerFirstReplay($consulting->memberId, $contentStr, $user->realname, $now);
            }

        });
    }

    private function getQuestionService(): QuestionService
    {
        return app(QuestionService::class);
    }

    private function getSynchronizer(): Synchronizer
    {
        return app(Synchronizer::class);
    }

    private function getSubscriptionMessageService(): SubscriptionMessageService
    {
        return app(SubscriptionMessageService::class);
    }

    private function getMiniProgramMessageService(): MiniProgramMessageService
    {
        return app(MiniProgramMessageService::class);
    }

    private function getDouyinMiniProgramMessageService(): DouyinMiniProgramMessageService
    {
        return app(DouyinMiniProgramMessageService::class);
    }

    private function getTemplateSmsService(): TemplateSmsService
    {
        return app(TemplateSmsService::class);
    }
}
